//
//  UIView+Extension.m
//  XiaoMiao
//
//  Created by 23 on 2017/11/4.
//  Copyright © 2017年 smallyou. All rights reserved.
//

#import "UIView+Extension.h"
#import <objc/runtime.h>

void Swizzle(Class c, SEL orig, SEL new) {
    Method origMethod = class_getInstanceMethod(c, orig);
    Method newMethod = class_getInstanceMethod(c, new);
    
    if (class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
        
    }else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

@implementation UIView (Extension)
+ (void)load {
    Swizzle(self, @selector(pointInside:withEvent:), @selector(myPointInside:withEvent:));
}

- (BOOL)myPointInside:(CGPoint)point withEvent:(UIEvent *)event {
    if (UIEdgeInsetsEqualToEdgeInsets(self.app_touchExtendInset, UIEdgeInsetsZero) || self.hidden ||
        ([self isKindOfClass:UIControl.class] && !((UIControl *)self).enabled)) {
        return [self myPointInside:point withEvent:event]; // 开始的实现方法
    }
    
    CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.app_touchExtendInset);
    hitFrame.size.height = MAX(hitFrame.size.height, 0);
    
    return CGRectContainsPoint(hitFrame, point);
}

static char touchExtendInsetKey;
- (void)setApp_touchExtendInset:(UIEdgeInsets)app_touchExtendInset {
    objc_setAssociatedObject(self, &touchExtendInsetKey, [NSValue valueWithUIEdgeInsets:app_touchExtendInset], OBJC_ASSOCIATION_RETAIN);
}

- (UIEdgeInsets)app_touchExtendInset {
    return [objc_getAssociatedObject(self, &touchExtendInsetKey) UIEdgeInsetsValue];
}


@end
